<template>
  <div class="user-manage-page">
    <div class="page-container">
      <!-- 页面标题 -->
<!--      <div class="page-header">
        <h1 class="page-title">用户管理</h1>
        <p class="page-subtitle">管理系统中的所有用户信息</p>
      </div>-->

      <!-- 搜索区域 -->
      <div class="search-card">
        <div class="search-header">
          <div class="search-icon">🔍</div>
          <h3>搜索用户</h3>
        </div>
        <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
          <a-form-item label="账号">
            <a-input
              v-model:value="searchParams.userAccount"
              placeholder="输入账号"
              class="search-input"
              allowClear
            />
          </a-form-item>
          <a-form-item label="用户名">
            <a-input
              v-model:value="searchParams.userName"
              placeholder="输入用户名"
              class="search-input"
              allowClear
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit" class="search-btn">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset" class="reset-btn">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 数据统计 -->
      <div class="stats-row">
        <div class="stat-card">
          <div class="stat-icon">👥</div>
          <div class="stat-content">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">👑</div>
          <div class="stat-content">
            <div class="stat-number">{{ adminCount }}</div>
            <div class="stat-label">管理员</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">👤</div>
          <div class="stat-content">
            <div class="stat-number">{{ userCount }}</div>
            <div class="stat-label">普通用户</div>
          </div>
        </div>
      </div>

      <!-- 用户表格 -->
      <div class="table-card">
        <div class="table-header">
          <h3>用户列表</h3>
          <div class="table-actions">
            <a-button @click="fetchData" class="refresh-btn">
              <template #icon><ReloadOutlined /></template>
              刷新
            </a-button>
          </div>
        </div>

        <a-table
          :columns="columns"
          :data-source="data"
          :pagination="pagination"
          @change="doTableChange"
          :loading="loading"
          class="user-table"
          :scroll="{ x: 1200 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'userAvatar'">
              <div class="avatar-container">
                <a-image
                  :width="50"
                  :height="50"
                  :src="record.userAvatar"
                  :preview="{
                    mask: '点击预览'
                  }"
                  class="user-avatar-image"
                />
              </div>
            </template>
            <template v-else-if="column.dataIndex === 'userRole'">
              <a-tag v-if="record.userRole === 'admin'" color="volcano" class="role-tag">
                <template #icon><CrownOutlined /></template>
                管理员
              </a-tag>
              <a-tag v-else color="blue" class="role-tag">
                <template #icon><UserOutlined /></template>
                普通用户
              </a-tag>
            </template>
            <template v-else-if="column.dataIndex === 'createTime'">
              <span class="time-text">
                {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
              </span>
            </template>
            <template v-else-if="column.dataIndex === 'userProfile'">
              <span class="profile-text" :title="record.userProfile">
                {{ record.userProfile || '暂无简介' }}
              </span>
            </template>
            <template v-else-if="column.key === 'action'">
              <div class="action-buttons">
                <a-button
                  type="primary"
                  size="small"
                  @click="handleEdit(record)"
                  class="edit-btn"
                >
                  <template #icon><EditOutlined /></template>
                  编辑
                </a-button>
                <a-popconfirm
                  title="确定要删除这个用户吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="doDelete(record.id)"
                >
                  <a-button
                    danger
                    size="small"
                    class="delete-btn"
                  >
                    <template #icon><DeleteOutlined /></template>
                    删除
                  </a-button>
                </a-popconfirm>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 编辑用户弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑用户信息"
      width="600px"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      :confirm-loading="editLoading"
      class="edit-modal"
    >
      <a-form
        :model="editForm"
        :rules="editRules"
        layout="vertical"
        ref="editFormRef"
        class="edit-form"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户账号" name="userAccount">
              <a-input
                v-model:value="editForm.userAccount"
                placeholder="请输入用户账号"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户名" name="userName">
              <a-input
                v-model:value="editForm.userName"
                placeholder="请输入用户名"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="用户头像" name="userAvatar">
          <a-input
            v-model:value="editForm.userAvatar"
            placeholder="请输入头像URL"
          />
          <div class="avatar-preview" v-if="editForm.userAvatar">
            <a-avatar :size="60" :src="editForm.userAvatar">
              <template #icon><UserOutlined /></template>
            </a-avatar>
          </div>
        </a-form-item>

        <a-form-item label="用户简介" name="userProfile">
          <a-textarea
            v-model:value="editForm.userProfile"
            placeholder="请输入用户简介"
            :rows="3"
            :maxlength="200"
            show-count
          />
        </a-form-item>

        <a-form-item label="用户角色" name="userRole">
          <a-select v-model:value="editForm.userRole" placeholder="请选择用户角色">
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { deleteUser, listUserVoByPage, updateUser } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  SearchOutlined,
  ReloadOutlined,
  UserOutlined,
  EditOutlined,
  DeleteOutlined,
  CrownOutlined
} from '@ant-design/icons-vue'

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
    fixed: 'left',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    width: 80,
    align: 'center',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    width: 120,
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    width: 120,
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
    width: 200,
    ellipsis: true,
  },
  {
    title: '角色',
    dataIndex: 'userRole',
    width: 100,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
    align: 'center',
  },
]

// 数据状态
const data = ref<API.UserVO[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 编辑相关状态
const editModalVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const editForm = reactive({
  id: undefined,
  userAccount: '',
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user',
})

// 编辑表单验证规则
const editRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 计算属性
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`,
    pageSizeOptions: ['10', '20', '50', '100'],
  }
})

// 统计数据
const adminCount = computed(() => {
  return data.value.filter(user => user.userRole === 'admin').length
})

const userCount = computed(() => {
  return data.value.filter(user => user.userRole === 'user').length
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listUserVoByPage({
      ...searchParams,
    })
    if (res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.total ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const doSearch = () => {
  searchParams.pageNum = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  searchParams.userAccount = ''
  searchParams.userName = ''
  searchParams.pageNum = 1
  fetchData()
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 删除用户
const doDelete = async (id: number) => {
  if (!id) {
    return
  }
  try {
    const res = await deleteUser({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      await fetchData()
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 编辑用户
const handleEdit = (record: API.UserVO) => {
  Object.assign(editForm, {
    id: record.id,
    userAccount: record.userAccount,
    userName: record.userName,
    userAvatar: record.userAvatar,
    userProfile: record.userProfile,
    userRole: record.userRole,
  })
  editModalVisible.value = true
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    editLoading.value = true

    const res = await updateUser({
      id: editForm.id,
      userName: editForm.userName,
      userAvatar: editForm.userAvatar,
      userProfile: editForm.userProfile,
      userRole: editForm.userRole,
    })

    if (res.data.code === 0) {
      message.success('更新成功')
      editModalVisible.value = false
      await fetchData()
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    message.error('更新失败')
  } finally {
    editLoading.value = false
  }
}

// 取消编辑
const handleEditCancel = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 页面加载时请求数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.user-manage-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2f5 100%);
  padding: 24px 0;
}

.page-container {
  max-width: 1500px;
  margin: 0 auto;
  padding: 0 24px;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #333;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.search-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 24px;
  margin-bottom: 24px;
}

.search-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.search-icon {
  font-size: 24px;
}

.search-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.search-form {
  gap: 16px;
}

.search-input {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.search-input:hover,
.search-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  font-weight: 600;
  margin-right: 12px;
}

.reset-btn {
  border: 1px solid #667eea;
  color: #667eea;
  border-radius: 8px;
  font-weight: 600;
}

.reset-btn:hover {
  background: #667eea;
  color: white;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  font-size: 32px;
  opacity: 0.8;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.table-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
}

.table-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.refresh-btn {
  border: 1px solid #667eea;
  color: #667eea;
  border-radius: 8px;
}

.refresh-btn:hover {
  background: #667eea;
  color: white;
}

.user-table {
  margin: 0;
}

.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-avatar-image {
  border-radius: 50%;
  border: 2px solid #f0f0f0;
  transition: all 0.3s ease;
  cursor: pointer;
}

.user-avatar-image:hover {
  border-color: #667eea;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.role-tag {
  font-weight: 600;
  border-radius: 12px;
  padding: 4px 12px;
}

.time-text {
  color: #666;
  font-size: 13px;
}

.profile-text {
  color: #666;
  display: block;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.edit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 6px;
  font-weight: 500;
}

.delete-btn {
  border-radius: 6px;
  font-weight: 500;
}

.edit-modal :deep(.ant-modal-header) {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
  border-bottom: 1px solid #f0f0f0;
}

.edit-form {
  padding-top: 16px;
}

.avatar-preview {
  margin-top: 12px;
  text-align: center;
}

/* 覆盖 Ant Design 样式 */
:deep(.ant-table-thead > tr > th) {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
  color: #333;
  font-weight: 600;
  border-bottom: 2px solid #f0f0f0;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(102, 126, 234, 0.03);
}

:deep(.ant-pagination) {
  margin: 24px;
  text-align: center;
}

:deep(.ant-form-item-label > label) {
  color: #333;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 0 16px;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .ant-form-item {
    margin-bottom: 16px;
  }

  .stats-row {
    grid-template-columns: 1fr;
  }

  .table-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 24px;
  }

  .stat-card {
    padding: 16px;
  }

  .stat-icon {
    font-size: 24px;
  }

  .stat-number {
    font-size: 20px;
  }
}
</style>
